const WebSocket = require('ws')
const http = require('http')
const { User, Document } = require('./db')

const port = 1234

// 存储所有连接的客户端
const clients = new Map() // 使用Map存储客户端和用户信息

// 创建HTTP服务器
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('WebSocket server for collaborative editor');
})

// 创建WebSocket服务器
const wss = new WebSocket.Server({ server })

wss.on('connection', (ws, req) => {
  console.log('New client connected')
  // 初始化客户端信息
  clients.set(ws, { id: null, name: null, color: null })
  
  // 发送欢迎消息
  ws.send(JSON.stringify({ type: 'connected', message: 'Connected to collaboration server' }))
  
  // 监听客户端消息
  ws.on('message', (message) => {
    try {
      const data = JSON.parse(message)
      console.log('Received message:', data)
      
      // 处理不同类型的用户消息
      switch (data.type) {
        case 'user-join':
          // 更新客户端信息
          clients.set(ws, data.user)
          // 广播新用户加入消息
          clients.forEach((userInfo, client) => {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
              client.send(JSON.stringify({
                type: 'user-join',
                user: data.user
              }))
            }
          })
          break
          
        case 'user-update':
          // 更新用户信息（如光标位置）
          const userInfo = clients.get(ws)
          if (userInfo) {
            clients.set(ws, { ...userInfo, ...data.user })
            // 广播用户更新消息
            clients.forEach((userInfo, client) => {
              if (client !== ws && client.readyState === WebSocket.OPEN) {
                client.send(JSON.stringify({
                  type: 'user-update',
                  user: { ...userInfo, ...data.user }
                }))
              }
            })
          }
          break
          
        case 'user-leave':
          // 广播用户离开消息
          const leavingUser = clients.get(ws)
          if (leavingUser) {
            clients.forEach((userInfo, client) => {
              if (client !== ws && client.readyState === WebSocket.OPEN) {
                client.send(JSON.stringify({
                  type: 'user-leave',
                  user: leavingUser
                }))
              }
            })
          }
          break
          
        case 'document-update':
          // 处理文档更新消息
          // 广播文档更新消息给所有其他客户端
          clients.forEach((userInfo, client) => {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
              client.send(JSON.stringify({
                type: 'document-update',
                content: data.content,
                documentId: data.documentId
              }))
            }
          })
          break
          
        default:
          // 广播其他消息给所有其他客户端
          clients.forEach((userInfo, client) => {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
              client.send(JSON.stringify(data))
            }
          })
      }
    } catch (error) {
      console.error('Error parsing message:', error)
    }
  })
  
  // 监听客户端断开连接
  ws.on('close', () => {
    console.log('Client disconnected')
    const userInfo = clients.get(ws)
    if (userInfo) {
      // 广播用户离开消息
      clients.forEach((info, client) => {
        if (client !== ws && client.readyState === WebSocket.OPEN) {
          client.send(JSON.stringify({
            type: 'user-leave',
            user: userInfo
          }))
        }
      })
    }
    clients.delete(ws)
  })
  
  // 监听错误
  ws.on('error', (error) => {
    console.error('WebSocket error:', error)
    clients.delete(ws)
  })
})

server.listen(port, () => {
  console.log(`WebSocket server running on ws://localhost:${port}`)
})